/**
 * 
 */
package com.swg.cocobox.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.LinkedList;
import java.util.List;

import com.swg.cocobox.KeyChange;

/**
 * @author satriaprayoga
 *
 */
public abstract class Server extends Thread{

	protected Selector selector;
	protected ServerSocketChannel serverChannel;
	
	protected InetAddress address;
	protected int port;
	
	protected List<KeyChange> keyChanges;
	
	public Server(InetAddress address,int port)throws IOException {
		this.address=address;
		this.port=port;
		this.keyChanges=new LinkedList<KeyChange>();
		this.selector=initSelector();
	}
	
	public Server(String host,int port)throws IOException{
		this(InetAddress.getByName(host),port);
	}
	
	public abstract void startServer();
	
	protected Selector initSelector()throws IOException{
		Selector serverSelector=SelectorProvider.provider().openSelector();
		serverChannel=ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		InetSocketAddress isa=new InetSocketAddress(address, port);
		serverChannel.socket().bind(isa);
		serverChannel.register(serverSelector, SelectionKey.OP_ACCEPT);
		return serverSelector;
	}
	
	protected abstract void accept(SelectionKey key)throws IOException;
	
	public void changeKey(SocketChannel channel,int ops){
		keyChanges.add(new KeyChange(channel, KeyChange.CHANGE, ops));
	}
	
	public void registerKey(SocketChannel channel,int ops){
		keyChanges.add(new KeyChange(channel, KeyChange.REGISTER, ops));
	}
}
